package com.xlg.file.center.handler;

import com.xlg.file.center.utils.Task;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * @author: 18310740596@163.com
 * @date: 2023-07-15 12:04:44
 * @version: v1.0
 * @describe: class responsibility
 */
public abstract class AbstractFileHandler implements IFileHandler {

    protected File createFile(Handler handler, String fileSuffix) throws IOException {
        // 创建文件名称
        String fileName = createFileName(handler.getTask(), fileSuffix);
        // 构建文件路径
        String filePath = buildFilePath(handler, fileName);
        // 创建文件
        return createFile(filePath);
    }

    private File createFile(String filePath) throws IOException {
        Path file = Files.createFile(Paths.get(filePath));
        return file.toFile();
    }

    private String createFileName(Task task, String fileSuffix) {
        String fileName = task.getFileName();
        if (StringUtils.isBlank(task.getFileName())) {
            fileName = UUID.randomUUID().toString().replaceAll("-", "");
        }
        return fileName.concat(fileSuffix);
    }

    private static String buildFilePath(Handler handler, String fileName) throws IOException {
        String filePath = handler.getFilePath();

        Path path = Paths.get(filePath);

        // 判断文件路径是否存在，如果不存在则需要创建
        if (!Files.exists(path)) {
            Files.createDirectory(path);
        }

        if (StringUtils.endsWith(filePath, File.separator)){
            filePath = filePath.concat(fileName);
        } else {
            filePath = filePath.concat(File.separator).concat(fileName);
        }
        return filePath;
    }
}
